package com.myMinistry.gui;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;

import com.myMinistry.R;
import com.myMinistry.provider.MinistryContract.Literature;
import com.myMinistry.provider.MinistryContract.LiteratureType;
import com.myMinistry.provider.MinistryService;

public class LiteratureEditor extends FragmentActivity {
	private CheckBox isActive;
	private EditText name;
	private MinistryService database;
	private int literatureID,literatureTypePosition,literatureTypeID = 0;
	private Spinner literatureTypes;
	
	@Override
	public void onStart() {
		super.onStart();
		if(literatureID > 0) {
			database.openReadable();
			Cursor record = database.fetchLiteratureByID(literatureID);
			if(record.moveToFirst()) {
				name.setText(record.getString(record.getColumnIndex(Literature.NAME)));
				if(record.getInt(record.getColumnIndex(Literature.ACTIVE)) == MinistryService.ACTIVE)
					isActive.setChecked(true);
			}
			record.close();
			database.close();
		}
	}
    
    @Override
	public void onStop() {
    	super.onStop();
    	database.close();
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        	startActivity(new Intent(getApplicationContext(), LiteratureManager.class));
			finish();
        }
        return super.onKeyDown(keyCode, event);
    }
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Bundle extras = getIntent().getExtras();
    	setContentView(R.layout.literature_editor);

    	if(extras != null) {
	    	Object[] keys = extras.keySet().toArray();
	    	for(int i = 0; i < keys.length; i++) {
	    		if(keys[i].toString().equals("literatureID"))
	    			literatureID = extras.getInt("literatureID");
	    		else if(keys[i].toString().equals("literatureTypePosition"))
	    			literatureTypePosition = extras.getInt("literatureTypePosition");
	    	}
	    }
    	
    	database = new MinistryService(this);
    	literatureTypes = (Spinner) findViewById(R.id.literatureTypes);
    	name = (EditText) findViewById(R.id.name);
    	isActive = (CheckBox) findViewById(R.id.isActive);
    	
    	findViewById(R.id.saveButton).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				save();
			}
		});
    	
    	database.openReadable();
	    Cursor types = database.fetchTypesOfLiterature();
	    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), android.R.layout.simple_spinner_item, types, new String[] {LiteratureType.NAME}, new int[]{android.R.id.text1});
    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	literatureTypes.setAdapter(adapter);
    	literatureTypes.setOnItemSelectedListener(
			new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent, View newview, int newposition, long newID) {
                	literatureTypeID = (int)newID;
                	literatureTypePosition = newposition;
                }
                public void onNothingSelected(AdapterView<?> parent) { }
            }
		);
    	database.close();
    	literatureTypes.setSelection(literatureTypePosition);
    }
	
	public void updatePublisher(int newPublisherID, String publisherName) {
		/** Update display name from fragment */
		ActionBarFragment fragment = (ActionBarFragment)getSupportFragmentManager().findFragmentById(R.id.action_bar_fragment);
		fragment.setSelectedPublisherNameText(publisherName);
	}
	
	public void showDialog() {
		/** DialogFragment.show() will take care of adding the fragment
		 * in a transaction. We also want to remove any currently showing
		 * dialogs, so make our own transaction and take care of that here. */
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if(prev != null)
			ft.remove(prev);
		ft.addToBackStack(null);
		/** Create and show the dialog. */
		DialogFrag newFragment = DialogFrag.newInstance(getApplicationContext().getString(R.string.menuPublishers), DialogFrag.ACTIVE_PUBLISHERS);
		newFragment.show(getSupportFragmentManager(), "dialog");
	}
	
	public void createNewPublisherShowDialog() {
		/** DialogFragment.show() will take care of adding the fragment
		 * in a transaction. We also want to remove any currently showing
		 * dialogs, so make our own transaction and take care of that here. */
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag("dialog");
		if(prev != null)
			ft.remove(prev);
		ft.addToBackStack(null);
		/** Create and show the dialog. */
		DialogFrag newFragment = DialogFrag.newInstance(getApplicationContext().getString(R.string.publishersName), DialogFrag.CREATE_PUBLISHER);
		newFragment.show(getSupportFragmentManager(), "dialog");
	}
	
	public void save() {
		ContentValues values = new ContentValues();
		values.put(Literature.NAME, name.getText().toString());
		values.put(Literature.PUBLISHER_ID, MinistryService.INACTIVE);
		values.put(Literature.TYPE_OF_LIERATURE_ID, literatureTypeID);
		values.put(Literature.ACTIVE, (isActive.isChecked()) ? MinistryService.ACTIVE : MinistryService.INACTIVE);
		values.put(Literature.SORT_ORDER, 0);
		database.openWritable();
		if(literatureID > 0)
			database.updateLiterature(literatureID, values);
		else {
			values.put(Literature.WEIGHT, 1);
			database.createLiterature(values);
		}
		database.close();
		Intent intent = new Intent(getApplicationContext(), LiteratureManager.class);
		intent.putExtra("literatureTypePosition", literatureTypePosition);
    	startActivity(intent);
		finish();
	}
}